<template>
  <div class="employees">
    <div class="app-container">
      <el-card>
        <template #header>
          <PageTools>
            <template #left>
              <span>总计{{ total }}条数据</span>
            </template>
            <template #right>
              <el-button
                v-if="canClick('exportExcel')"
                type="primary"
                size="small"
                @click="$router.push('import')"
              >
                导入excel
              </el-button>
              <el-button
                type="primary"
                size="small"
                :loading="downloadLoading"
                @click="exportData"
              >
                导出excel
              </el-button>
              <el-button type="primary" size="small" @click="showDialog = true">
                新增员工
              </el-button>
            </template>
          </PageTools>
        </template>
        <!-- table列表 -->
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'workNumber', order: 'descending' }"
        >
          <el-table-column type="index" label="序号">
            <template #default="scope">
              <span>{{
                (query.page - 1) * query.size + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="username" label="头像">
            <template #default="{ row }">
              <el-image
                class="photo"
                :src="row.staffPhoto"
                fit="cover"
                @click="openCode(row.staffPhoto)"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formatFormOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable prop="correctionTime" label="入职时间" />
          <el-table-column label="账户状态">
            <el-switch v-model="qy" />
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                v-if="canClick('p-em-look')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="openAssignRole(row.id)"
              >
                分配角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployees(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            :page-size="query.size"
            :current-page="query.page"
            :page-sizes="[10, 2, 5]"
            layout="prev, pager, next, sizes"
            @current-change="changePage"
            @size-change="changeSizes"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 添加的对话框 -->
    <AddEmployees :show-dialog.sync="showDialog" />
    <!-- 二维码组件 -->
    <QrCode ref="qr" :dialog-visible.sync="dialogVisible" />
    <!-- 分配角色弹窗 -->
    <AssignRole ref="ar" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
// 导入数据词典映射
import diction from '@/api/constant/employees.js'
// 引入对话框
import AddEmployees from './components/add-employee.vue'
// 导入二维码组件
import QrCode from './components/qr-code.vue'
// 导入分配角色弹框
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployees,
    QrCode,
    AssignRole
  },
  data () {
    return {
      // 分配角色的弹框显示与隐藏
      showRoleDialog: false,
      // 二维码框的显示隐藏
      dialogVisible: false,
      // 加载效果
      downloadLoading: false,
      // 对话框的显示与隐藏
      showDialog: false,
      // 账户状态
      qy: true,
      // 列表数据
      list: [],
      // 分页数据
      query: {
        page: 1,
        size: 10
      },
      // 总条数
      total: 0
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 点击分配角色
    openAssignRole (id) {
      this.showRoleDialog = true
      this.$refs.ar.getRoleListData(id)
    },
    // 点击图片显示对话框
    openCode (url) {
      this.dialogVisible = true
      this.$refs.qr.draw(url)
    },
    // 导出Excel表格
    async exportData () {
      this.downloadLoading = true
      const excel = await import('@/utils/Export2Excel')
      const { header, secondArray } = this.transformExcel()
      excel.export_json_to_excel({
        header,
        data: secondArray,
        filename: `第${this.query.page}页员工数据`,
        autoWidth: true,
        bookType: 'xlsx'
      })
      this.downloadLoading = false
    },
    // 处理导出的数据
    transformExcel () {
      const headerMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 标题
      const header = Object.keys(headerMap)
      // 映射的值
      const mapValue = Object.values(headerMap)
      const secondArray = []
      this.list.forEach(item => {
        const userInfo = []
        for (const key in item) {
          if (mapValue.includes(key)) {
            if (key === 'formOfEmployment') {
              userInfo.push(this.formatFormOfEmployment(item[key]))
            } else {
              userInfo.push(item[key])
            }
          }
        }
        secondArray.push(userInfo)
      })

      return { header, secondArray }
    },
    // 删除列表
    async delEmployees (row) {
      try {
        await this.$confirm(`确定删除:${row.username}吗？`, '提示')
        await delEmployee(row.id)
        if (this.list.length === 1 && this.query.page > 1) {
          this.query.page--
        }
        this.getList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 聘用形式的转换
    formatFormOfEmployment (type) {
      const map = {}
      diction.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 获取数据列表
    async getList () {
      const { rows, total } = await getEmployeeList(this.query)
      this.list = rows
      this.total = total
    },
    // 分页变化的函数
    changePage (page) {
      this.query.page = page
      this.getList()
    },
    // 页码数变化
    changeSizes (size) {
      this.query.size = size
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.photo {
  width: 100px;
  height: 100px;
  border-radius: 100%;
}
</style>
